#!/usr/bin/env python
# -*- coding: utf-8 -*-
#code:utf-8
#
# Copyright(C) 2011 SupDo.com
# Licensed under the GUN License, Version 3.0 (the "License");
# 
# File:        userForm.py
# Author:      KuKei
# Create Date: 2011-04-18
# Description: 系统部分表单
# Modify Date: 2012-05-28

import hashlib
from django import forms
from sd.cms.forms import BaseForm, BaseModelForm
from sd.cms.models.userModel import User

# 疑问： UserForm和LoginForm如何复用，LoginForm是UserForm的一个子集
class UserForm(BaseModelForm):
    repassword  = forms.CharField(max_length=32, label="确认密码", widget=forms.PasswordInput)
    
    cValid = ['username','password','repassword','nickname','sex','froms','mobile','email','qq','birthday']
    def clean(self):
        if self.data.has_key('password') and self.data.has_key('repassword'):
            if self.data['password'] <> self.data['repassword']:
                self._errors["repassword"] = self.error_class(['密码和确认密码不一致！'])
        return self.cleaned_data
    
    class Meta:
        model = User
        fields = ('username','password','repassword','nickname','sex','froms','mobile','email','qq','birthday','homepage','alipay','introduction')
        widgets = {
            'password': forms.PasswordInput,
            'repassword': forms.PasswordInput,
        }
    
class LoginForm(BaseForm):
    username  = forms.CharField(max_length=30, min_length=4, label="用户名")
    password  = forms.CharField(max_length=30, min_length=1, label="密码", widget=forms.PasswordInput)
    safecode  = forms.CharField(max_length=4, min_length=4, label="验证码", widget=forms.HiddenInput)
    
    cValid = ['username','password']
    #自定义验证
    def clean_safecode(self):
        safecode = self.data['safecode']
        if self.bv.request.session.has_key(self.bv.params.SAFECODE):
            if hashlib.sha1(safecode).hexdigest() != self.bv.request.session[self.bv.params.SAFECODE]:
                raise forms.ValidationError("验证码不正确!")
        else:
            raise forms.ValidationError("验证码的Session不存在!")
        return safecode
    
    def clean_password(self):
        password = hashlib.sha1(self.data['password']).hexdigest()
        return password
    
    class Meta:
        fields = ('username', 'password', 'safecode')
        widgets = {
            'password': forms.PasswordInput,
        }
